<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
    <title>聊天列表-在线聊天室</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <style>
        body {
            font-family: 'Arial', sans-serif;
        }

        .chat-area {
            height: 480px;
            flex-grow: 1;
            overflow-y: auto;
            padding: 1rem;
            background-color: #f8f9fa;
        }

        .chat-input {
            margin-top: auto;
        }

        .chat-message {
            margin-bottom: 1rem;
        }

        .chat-message.right {
            text-align: right;
        }

        .chat-message.right img {
            margin-left: 5px;
        }

        .chat-message.right .message-bubble {
            background-color: #007bff;
            color: white;
        }

        .chat-message.left {
            text-align: left;
        }

        .message-bubble {
            display: inline-block;
            padding: 0.5rem 1rem;
            border-radius: 1rem;
            background-color: #e9ecef;
            max-width: 70%;
        }

        .avatar {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            margin-right: 10px;
            vertical-align: middle;
        }

        .time-stamp {
            font-size: 10px;
            display: block;
            margin-top: 5px;
        }
        .red-dot {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            background-color: red;
            display: inline-block;
            margin-left: 5px;
        }
        .not-message {
            text-align: center;
        }

    </style>
</head>
<body>
<div class="container-fluid">
    <div class="row">
        <!-- 侧边栏 -->
        <div class="col-md-3 bg-light p-3 sidebar">
            <ul class="list-group">
                <th:block th:each="chat : ${chats}">
                    <li class="list-group-item list-group-item-action"
                        th:name="${chat.chatId}"
                        th:type="${chat.chatType}"
                        th:value="${chat.receiverId}">
                        <img src="images/qq.png" th:src="${chat.chatAvatar}" width="20" height="20"/>
                        <span th:text="${chat.chatName}">聊天列表1</span>
                        <!-- 显示未读消息数的元素 -->
                        <span class="unread-count badge bg-danger" th:value="${chat.count}" th:if="${chat.count != null and chat.count > 0}" th:text="${chat.count}"></span>
                        <!-- 红点标记元素 -->
                        <span class="red-dot" th:if="${chat.count != null and chat.count > 0}"></span>
                    </li>
                </th:block>
            </ul>
        </div>

        <!-- 主要内容 -->
        <div class="col-md-9 main-content">
            <div class="chat-area">

            </div>
            <div class="chat-input">
                <div class="input-group mb-3">
                    <input type="text" class="form-control" id="message" placeholder="输入消息..."
                           aria-label="Recipient's username" aria-describedby="basic-addon2">
                    <button class="btn btn-primary" type="button" id="send">发送</button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 引入 JavaScript -->
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/common.js"></script>

<!--在js脚本中获取作用域的值-->
<script th:inline="javascript">
    //获取session中的user
    var user = [[${session.user}]];
    //获取ws服务地址
    var ws = [[${ws}]]
</script>

<!-- 建立连接 -->
<script type="text/javascript">
    var websocket;
    if (!window.WebSocket) {
        window.WebSocket = window.MozWebSocket;
    }
    if (window.WebSocket) {
        websocket = new WebSocket(ws + "?userId=" + user.id);
        websocket.onmessage = function (event) {
            var json = JSON.parse(event.data);
            console.log('接收消息', json)
            chat.onmessage(json);
        };
        websocket.onopen = function (event) {
            console.log("Netty-WebSocket服务器。。。。。。连接");
        };
        websocket.onclose = function (event) {
            console.log("Netty-WebSocket服务器。。。。。。关闭");
        };
    } else {
        alert("您的浏览器不支持WebSocket协议！");
    }
    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function () {
        if (websocket != null) {
            websocket.close();
        }
    };
</script>


<script type="text/javascript">
    var chat = {
        // 发送消息给 websocket 对象
        sendMessage: function () {
            let message = $("#message").val();

            // 判断消息是否为空
            if (message === "") {
                alert("不能发送空消息！")
                return
            }

            // 判断浏览器是否支持WebSocket
            if (!window.WebSocket) {
                return
            }

            // 获取聊天室id
            let receiverId = $(".list-group-item.active").attr("value")
            let chatId = $(".list-group-item.active").attr("name")
            let chatType = $(".list-group-item.active").attr("type")

            if (!chatId) {
                alert('请选择聊天列表发送消息！')
                return
            }

            // 判断连接是否已经打开
            if (websocket.readyState === WebSocket.OPEN) {
                let data = {
                    chatId: chatId,
                    receiverId: receiverId,
                    sendId: user.id,
                    content: message,
                    avatar: user.avatar,
                    time: getNowTime(),
                    messageType: 'text'
                }
                console.log('send message', data)
                websocket.send(JSON.stringify(data))

                // 添加消息
                addMessage('right', user.avatar, data.content, data.time)
            } else {
                alert("和服务器连接异常！");
            }
        },

        // 接收消息
        onmessage: function (jsonData) {
            // 如果是群聊并且是自己不添加消息
            if (jsonData.chatType === 2 && jsonData.sendId === user.id) {
                return
            }

            // 如果是当前聊天室才添加消息
            let chatId = $(".list-group-item.active").attr("name")
            if (jsonData.chatId == chatId) {
                // 添加消息
                addMessage('left', jsonData.avatar, jsonData.content, jsonData.time)
            }
        }
    }

    // 监听回车事件
    document.onkeydown = function (e) {
        // 兼容FF和IE和Opera    
        var theEvent = e || window.event;
        var code = theEvent.keyCode || theEvent.which || theEvent.charCode;
        // 13 代表 回车键
        if (code === 13) {
            // 要执行的函数 或者点击事件
            chat.sendMessage();
            return false;
        }
        return true;
    };


    $(document).ready(function () {
        // 发送消息
        $('#send').click(function () {
            chat.sendMessage()
            $("#message").val('')
        });

        // 选择用户或群聊
        $(".list-group-item-action").click(function () {
            $(this).addClass("active")
            $(this).siblings().removeClass("active")
            initChat($(this))
        });
    });


    /**
     * 初始化聊天
     * @param item 元素
     */
    function initChat(item) {
        // 清空聊天记录
        $(".chat-area").empty();
        // 添加选中样式
        item.addClass("active");

        // 获取聊天ID
        let chatId = item.attr("name")
        // 获取聊天类型
        let chatType = item.attr("type")

        $.get("/chat/get/" + chatId, function (res) {
            // 聊天信息
            let message = res.data.messages;

            // 检查是否有聊天记录
            if (message.length < 1) {
                $('.chat-area').append($('<div>').text("暂时没有消息哦！").addClass("not-message"))
                return
            }

            // 聊天成员
            let member = res.data.members

            // 渲染聊天
            for (let j = 0; j < message.length; j++) {
                // 自己发送的消息渲染左边
                if (message[j].sendId != user.id) {
                    // 群聊渲染用户头像
                    if (chatType == 2) {
                        for (let k = 0; k < member.length; k++) {
                            if (member[k].id == message[j].sendId) {
                                addMessage('left', member[k].avatar, message[j].content, message[j].time, chatId)
                            }
                        }
                    } else {
                        addMessage('left', res.data.chatAvatar, message[j].content, message[j].time, chatId)
                    }
                } else {
                    addMessage('right', user.avatar, message[j].content, message[j].time, chatId)
                }
            }

        })

    }

    /**
     * 添加消息
     * @param sender 方向
     * @param avatar 头像
     * @param message 消息
     * @param time 时间
     */
    function addMessage(sender, avatar, message, time, chatId) {
        $(".not-message").remove()
        let $chatMessage = $('<div>', {class: 'chat-message ' + sender});
        let $chat = $("<div>", {class: 'message-bubble'});

        if (sender == 'left') {
            $chat.append($("<img>", {src: avatar, alt: 'avatar', class: 'avatar'}));
            $chat.append(message)
        } else {
            $chat.append(message)
            $chat.append($("<img>", {src: avatar, alt: 'avatar', class: 'avatar'}))
        }

        $chat.append($("<span>", {class: 'time-stamp', html: time}))
        $chatMessage.append($chat)

        $('.chat-area').append($chatMessage)

        $chat.find(".avatar").on('click', function () {
            if (sender == 'left') {
                window.location.href = 'detail/' + chatId;
            } else if (sender == 'right') {
                window.location.href = '/profile';
            }
        })
        scrollToBottom()
    }


    // 滚动到底部
    function scrollToBottom() {
        var chatArea = $('.chat-area');
        chatArea.scrollTop(chatArea[0].scrollHeight);
    }

    // 获取url参数
    window.onload = function () {
        const urlParams = new URLSearchParams(window.location.search);
        let chatId = urlParams.get('chatId');

        if (chatId != null) {
            $("[name='" + formatChatId(chatId) + "']").click();
        }
    }


    function formatChatId(chatId){
        if(chatId.indexOf("user") != -1){
            const arr = chatId.split("-").slice(1)
            const sender = arr[0]
            const receiver = arr[1]

            if (sender < receiver) {
                return `user-${sender}-${receiver}`;
            } else {
                return `user-${receiver}-${sender}`;
            }
        }else{
            return chatId;
        }
    }
</script>
</body>
</html>
